import 'dart:math';

import '../config/device_config.dart';
import '../config/production_data_config.dart';
import '../config/alarm_config.dart';
import '../config/air_conditioner_config.dart';
import '../config/maintenance_config.dart';
import '../models/status_models.dart';
import '../models/production_data_models.dart';
import '../models/alarm_models.dart';
import '../models/air_conditioner_status.dart';
import '../models/maintenance_models.dart';

class MockDataService {
  static Future<List<DeviceInfo>> getDeviceInfo() async {
    final deviceConfigs = await getDeviceInfoConfig();
    return deviceConfigs.map((config) {
      // 将point_value转换为状态：0=关闭，1=运行
      // 对于非0非1的值，根据是否大于0来判断状态
      final pointValue = (config['point_value'] as num?)?.toDouble() ?? 0.0;
      int status;
      if (pointValue == 0.0) {
        status = 0; // 关闭
      } else if (pointValue == 1.0) {
        status = 1; // 运行
      } else {
        // 对于其他值（如30549.0），根据是否大于0来判断
        status = pointValue > 0 ? 1 : 0;
      }
      
      return DeviceInfo(
        name: config['name'] as String,
        cubicleNo: config['cubicleNo'] as String,
        deviceNo: config['deviceNo'] as String,
        tag: config['tag'] as String,
        status: status,
      );
    }).toList();
  }

  static Future<List<AirConditionerInfo>> getXF01AirConditionerInfo() async {
    final xf01Data = await getXf01Data();
    return xf01Data.map((status) => AirConditionerInfo(
      label: status.label,
      address: status.address,
      dataType: 'BOOL',
      status: status.status ? 1 : 0,
    )).toList();
  }

  static Future<List<AirConditionerInfo>> getXF02AirConditionerInfo() async {
    final xf02Data = await getXf02Data();
    return xf02Data.map((status) => AirConditionerInfo(
      label: status.label,
      address: status.address,
      dataType: 'BOOL',
      status: status.status ? 1 : 0,
    )).toList();
  }

  static AirConditionerInfo getAirConditionerInfo(Map<String, dynamic> config) {
    // Extract last 4 characters from address (e.g., 'DB3.DBX42.0' -> 'X42.0')
    String originalAddress = config['address'] as String;
    String shortAddress = originalAddress.length >= 4 ? originalAddress.substring(originalAddress.length - 4) : originalAddress;
    
    return AirConditionerInfo.fromJson({
      'label': config['label'],
      'address': shortAddress,
      'dataType': config['dataType'],
      'status': Random().nextInt(2),
    });
  }

  static List<AirSourceUnitInfo> getAirSourceUnitInfo() {
    return airSourceUnitConfig.map((config) {
      return AirSourceUnitInfo.fromJson({
        'label': config['label'],
        'address': config['address'],
        'dataType': config['dataType'],
        'status': Random().nextInt(2),
      });
    }).toList();
  }

  static Map<String, List<dynamic>> getAlarmData() {
    return {
      'smartAirOutletAlarms': alarmConfig['smartAirOutletAlarms']!
          .map((config) => SmartAirOutletAlarm.fromJson(_getMockAlarm(config)))
          .toList(),
      'cubicleAirConditionerControlCabinetAlarms': alarmConfig['cubicleAirConditionerControlCabinetAlarms']!
          .map((config) => CubicleAirConditionerControlCabinetAlarm.fromJson(_getMockAlarm(config)))
          .toList(),
      'xf01AirConditionerAcquisitionAlarms': alarmConfig['xf01AirConditionerAcquisitionAlarms']!
          .map((config) => AirConditionerAcquisitionAlarm.fromJson(_getMockAlarm(config)))
          .toList(),
      'xf02AirConditionerAcquisitionAlarms': alarmConfig['xf02AirConditionerAcquisitionAlarms']!
          .map((config) => AirConditionerAcquisitionAlarm.fromJson(_getMockAlarm(config)))
          .toList(),
      'airSourceUnitAlarms': alarmConfig['airSourceUnitAlarms']!
          .map((config) => AirSourceUnitAlarm.fromJson(_getMockAlarm(config)))
          .toList(),
    };
  }

  static Map<String, dynamic> _getMockAlarm(Map<String, dynamic> config) {
    // 让一些特定的报警显示为活跃状态以便测试
    int status = 0;
    if (config['name'].toString().contains('XF-01空调控制柜通讯故障') ||
        config['name'].toString().contains('XF-02空调控制柜通讯故障') ||
        config['name'].toString().contains('空气源模块机组') ||
        config['name'].toString().contains('方舱空调')) {
      status = 1; // 活跃状态
    } else {
      status = Random().nextInt(3) == 0 ? 1 : 0; // 33%概率为活跃
    }
    
    return {
      'label': config['label'],
      'address': config['address'],
      'type': config['type'],
      'name': config['name'],
      'status': status,
    };
  }

  static Map<String, List<dynamic>> getProductionData() {
    return {
      'cubicleAirConditionerData': _getMockProductionData(
          productionDataConfig['cubicleAirConditionerData'] ?? [],
          (json) => CubicleAirConditionerData.fromJson(json)),
      'smartAirOutletData': _getMockProductionData(
          productionDataConfig['smartAirOutletData'] ?? [],
          (json) => SmartAirOutletData.fromJson(json)),
      'airOutletUsageTime': <dynamic>[],
      'airConditionerUnitData': <dynamic>[],
      'airSourceModuleData': <dynamic>[],
      'dustParticleMonitorData': <dynamic>[],
    };
  }

  static List<T> _getMockProductionData<T>(
      List<Map<String, dynamic>> config, T Function(Map<String, dynamic>) fromJson) {
    return config.map((item) {
      final value = Random().nextDouble() * 100;
      return fromJson({
        ...item,
        'value': value,
      });
    }).toList();
  }

  /// 获取维护数据
  /// 现在roomExhaustControl数据从API获取
  static Future<Map<String, List<dynamic>>> getMaintenanceData() async {
    // 获取包含API数据的配置
    final config = await MaintenanceDataConfig.getMaintenanceDataConfig();
    
    return {
      'smartAirOutletControl': _getMockMaintenanceData(
          config['smartAirOutletControl'] ?? [],
          (json) => SmartAirOutletControl(
            name: json['name'] ?? '',
            cubicleNo: json['cubicleNo'] ?? '',
            deviceNo: json['deviceNo'] ?? '',
            tag: json['tag'] ?? '',
            address: json['address'] ?? '',
            dataType: json['dataType'] ?? '',
            dataName: json['dataName'] ?? '',
            unit: json['unit']?.toString() ?? '', // 确保null值转换为空字符串
          )),
      'airOutletUsageTimeReset': _getMockMaintenanceData(
          config['airOutletUsageTimeReset'] ?? [],
          (json) => AirOutletUsageTimeReset(
            name: json['name'] ?? '',
            cubicleNo: json['cubicleNo'] ?? '',
            deviceNo: json['deviceNo'] ?? '',
            tag: json['tag'] ?? '',
            address: json['address'] ?? '',
            dataType: json['dataType'] ?? '',
          )),
      'roomPressureDifferenceControl': _getMockMaintenanceData(
          config['roomPressureDifferenceControl'] ?? [],
          (json) => RoomPressureDifferenceControl(
            name: json['name'] ?? '',
            cubicleNo: json['cubicleNo'] ?? '',
            deviceNo: json['deviceNo'] ?? '',
            tag: json['tag'] ?? '',
            address: json['address'] ?? '',
            dataType: json['dataType'] ?? '',
            dataName: json['dataName'] ?? '',
            unit: json['unit']?.toString() ?? '', // 确保null值转换为空字符串
          )),
      // 房间排风控制数据现在从API获取
      'roomExhaustControl': _getMockMaintenanceData(
          config['roomExhaustControl'] ?? [],
          (json) => RoomExhaustControl(
            name: json['cabin_name'] ?? json['name'] ?? '',
            cubicleNo: json['cabin_id'] ?? json['cubicleNo'] ?? '',
            deviceNo: json['device_id'] ?? json['deviceNo'] ?? '',
            tag: json['tag'] ?? '',
            address: json['address'] ?? '',
            dataType: 'REAL', // API数据中没有dataType字段，使用默认值
            dataName: json['module_name'] ?? json['dataName'] ?? '',
            unit: json['unit']?.toString() ?? '', // 确保null值转换为空字符串
          )),
      'xf01AirConditionerUnitControl': _getMockMaintenanceData(
          config['xf01AirConditionerUnitControl'] ?? [],
          (json) => AirConditionerUnitControl(
            tag: json['tag'] ?? '',
            address: json['address'] ?? '',
            dataType: json['dataType'] ?? '',
            name: json['name'] ?? '',
            unit: json['unit']?.toString() ?? '', // 确保null值转换为空字符串
            remark: json['remark'] ?? '',
          )),
      'xf02AirConditionerUnitControl': _getMockMaintenanceData(
          config['xf02AirConditionerUnitControl'] ?? [],
          (json) => AirConditionerUnitControl(
            tag: json['tag'] ?? '',
            address: json['address'] ?? '',
            dataType: json['dataType'] ?? '',
            name: json['name'] ?? '',
            unit: json['unit']?.toString() ?? '', // 确保null值转换为空字符串
            remark: json['remark'] ?? '',
          )),
    };
  }

  static List<T> _getMockMaintenanceData<T>(
      List<Map<String, dynamic>> config, T Function(Map<String, dynamic>) fromJson) {
    return config.map((item) {
      return fromJson(item);
    }).toList();
  }
}